package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 计算营业额数据
     * @param startDate
     * @param endDate
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate startDate, LocalDate endDate) {
        //构造当前日期之间所有日期的集合
        List<LocalDate> dates = new ArrayList<>();
        while (startDate.isBefore(endDate)) {
            dates.add(startDate);
            startDate = startDate.plusDays(1);
        }
        dates.add(endDate);
        //转换为字符串
        String dateListString = StringUtils.join(dates, ", ");

        //查询对应的每天营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dates) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);

            Double turnover = orderMapper.subByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);

        }

        //转换为字符串
        String turnoverListString = StringUtils.join(turnoverList, ", ");

        log.info("营业额相关数据：{}，{}", dateListString, turnoverListString);

        return TurnoverReportVO
                .builder()
                .dateList(dateListString)
                .turnoverList(turnoverListString)
                .build();
    }

    /**
     * 计算用户数据
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate startDate, LocalDate endDate) {
        //构造当前日期之间所有日期的集合
        List<LocalDate> dates = new ArrayList<>();
        while (startDate.isBefore(endDate)) {
            dates.add(startDate);
            startDate = startDate.plusDays(1);
        }
        dates.add(endDate);
        //转换为字符串
        String dateListString = StringUtils.join(dates, ", ");

        //存放新用户
        List<Integer> newUser = new ArrayList<>();
        //存放全部用户
        List<Integer> allUser = new ArrayList<>();

        for (LocalDate date : dates) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("endTime", endTime);
            Integer userCountAll = orderMapper.countByMap(map);
            userCountAll = userCountAll == null ? 0 : userCountAll;
            allUser.add(userCountAll);

            map.put("beginTime", beginTime);
            Integer userCountNew = orderMapper.countByMap(map);
            userCountNew = userCountNew == null ? 0 : userCountNew;
            newUser.add(userCountNew);
        }
        //转换为字符串
        String newUserListString = StringUtils.join(newUser, ", ");
        //转换为字符串
        String allUserListString = StringUtils.join(allUser, ", ");

        return UserReportVO
                .builder()
                .dateList(dateListString)
                .newUserList(newUserListString)
                .totalUserList(allUserListString)
                .build();
    }

    /**
     * 订单统计
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate startDate, LocalDate endDate) {
        //构造当前日期之间所有日期的集合
        List<LocalDate> dates = new ArrayList<>();
        while (startDate.isBefore(endDate)) {
            dates.add(startDate);
            startDate = startDate.plusDays(1);
        }
        dates.add(endDate);
        //转换为字符串
        String dateListString = StringUtils.join(dates, ", ");


        //存放新用户
        List<Integer> successOrdersList = new ArrayList<>();
        //存放全部用户
        List<Integer> allOrdersList = new ArrayList<>();
        //订单总数
        Integer allOrders = 0;
        //有效订单总数
        Integer successOrders = 0;
        //遍历日期集合，获得订单总数，有效订单数
        for (LocalDate date : dates) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //先算订单总数
            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            allOrdersList.add(orderMapper.countStatusByMap(map));
            allOrders += orderMapper.countStatusByMap(map);

            //在计算有效订单数
            map.put("status", Orders.COMPLETED);
            successOrdersList.add(orderMapper.countStatusByMap(map));
            successOrders += orderMapper.countStatusByMap(map);
        }

        //转化为字符串
        String successOrdersListString = StringUtils.join(successOrdersList, ", ");
        String allOrdersListString = StringUtils.join(allOrdersList, ", ");

        //计算订单完成率
        Double finishingRate = successOrders.doubleValue() / allOrders.doubleValue();
        return OrderReportVO
                .builder()
                .dateList(dateListString)
                .orderCountList(allOrdersListString)
                .validOrderCountList(successOrdersListString)
                .totalOrderCount(allOrders)
                .validOrderCount(successOrders)
                .orderCompletionRate(finishingRate)
                .build();
    }

    /**
     * 销量前十统计
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10Statistics(LocalDate startDate, LocalDate endDate) {
        LocalDateTime beginTime = LocalDateTime.of(startDate, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(endDate, LocalTime.MAX);
        //调用mapper获取数据
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        List<String> names =  salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameListString = StringUtils.join(names, ", ");
        List<Integer> numbers =  salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberListString = StringUtils.join(numbers, ", ");
        return SalesTop10ReportVO
                .builder()
                .nameList(nameListString)
                .numberList(numberListString)
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1. 查询数据库，获取营业数据---查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);

                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                System.out.println(businessData.toString());
                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
